const App = {
    mixins: [Query],//配置文件，路径/utils/mixins.js
    data() {
        return {
            photo,
            page: {
                activeName: 'first',
                value1: '',
                value2:'',
                PageNumber: 1, //页码
                RowAmount: 20,
                Condition: window.btoa(unescape(encodeURIComponent("%%,0"))),
                ExtensionCondition: window.btoa(unescape(encodeURIComponent("")))
            },
            str1: '',
            str: '',
            fileUrl:'',
            showDialog1:false,
            showDialog2:false,
            message_board_attachment:[],
            form1:{},
            form:{}
        }
    },
    mounted() {

    },
    methods: {
        check() {

            this.page.Condition = window.btoa(unescape(encodeURIComponent("%" + this.page.value1  + "%,%" +( this.page.value2 || '' )+ "%")));
            this.postgetList(this.page);
        },
        preview(row) {
            this.fileUrl = photo + row.Attachment_Path;
            this.showDialog = true;
        },
        async download(row) {
            // if (row.Attachment_Path) {
            //     window.location.href = photo + row.Attachment_Path;
            // }
            let apiUrl = photo + row.Attachment_Path;
            let fileName = apiUrl.split('/').pop();
            
            try {
                const response = await fetch(apiUrl);
                const blob = await response.blob();
                const url = window.URL.createObjectURL(blob);
                
                const a = document.createElement('a');
                a.href = url;
                a.download = fileName || 'download';
                document.body.appendChild(a);
                a.click();
                
                // 清理
                setTimeout(() => {
                    document.body.removeChild(a);
                    window.URL.revokeObjectURL(url);
                }, 100);
            } catch (error) {
                console.error('下载失败:', error);
            }
        },
        handlehf(row){
            this.form = {
                Comment_Object_SerialNumber:row.Message_SerialNumber,
                Parent_SerialNumber: '',
                Comment_Type:'2',
                Public_Datetime:getYMDHMSDate(),
                IP_Address:getIpAddress(),
            };
            this.showDialog1 = true
        },
        handleShow(row){
            window.location.href = './show.html?action=Add&Message_SerialNumber=' + row.Message_SerialNumber
        },
        handleShow1(row) {
            let { primary_key } = JSON.parse(document.getElementById("table").getAttribute("data-options"));
                $.ajax({
                    headers: requestHeaders(),
                    url: `${mh}/generalBusiness/generalQueryByTableNameWithOriginal`,
                    method: "post",
                    data: {
                        Data: 'message_board_attachment',
                        Condition: primary_key + "='" + row[primary_key] + "'"
                    },
                    success: (res) => {
                        this.message_board_attachment = res;
                        this.showDialog2 = true;
                    }, complete: (XMLHttpRequest) => {

                        requestPretreatment(XMLHttpRequest);
                    }
                });
        },
        async validateAllForms() {
            //获取当前页面上所有的Elform
            let forms = [];
            for (let key in this.$refs) {
                const ref = this.$refs[key];
                if (ref.$options && ref.$options.name == 'ElForm') {
                    forms.push(ref);
                }
            }
            //判断每个Elform的校验是否通过
            let isfail = false;
            for (const form of forms) {
                try {
                    await form.validate();
                } catch (error) {
                    isfail = true;
                }
            }
            if (isfail) {
                return false;
            }
            return true;
        },
        async handleSubmit(){
            const allValid = await this.validateAllForms();
            if (allValid) {
                this.loading = true;
                let lJSONObject_DataSet = {
                    Add:{comments :[this.form]} 
                }
                let Operation_Main = JSON.stringify(deepClone(lJSONObject_DataSet));
                lJSONObject_DataSet['Add']['base_operation_log'] = [{
                    Operation_Type: '0',
                    Operation_Path: this.relativePath,
                    Operation_Main,
                    Operation_Interface: "generalSaveByRequestBody",
                    Operation_IP: getIpAddress()
                }]
                submitSave(lJSONObject_DataSet,(res)=>{
                    if (res.Status == 'success') {
                        this.showDialog1 = false
                        this.postgetList(this.page)
                    }
                    this.loading = false;
                })
                // $.ajax({
                //     headers: requestHeaders("JSON"),
                //     url: `${mh}/generalBusiness/generalSaveByRequestBody`,
                //     method: "post",
                //     data: JSON.stringify({
                //         Data: lJSONObject_DataSet,
                //     }),
                //     success: (res) => {
                //         if (res.Status == 'success') {
                //             this.showDialog1 = false
                //             this.postgetList(this.page)
                //         }
                //     },
                //     complete: (XMLHttpRequest) => {
                //         this.loading = false;
                //         requestPretreatment(XMLHttpRequest)
                //     }
                // });
            }
        },
        handle2(row) {
            this.$confirm('是否' + (row.Is_Sticky == '0' ? '置顶' : '取消置顶') + '该数据', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }).then(() => {
                let { TableName, primary_key } = JSON.parse(document.getElementById("table").getAttribute("data-options"));
                $.ajax({
                    headers: requestHeaders(),
                    url: `${mh}/generalBusiness/generalQueryByTableNameWithOriginal`,
                    method: "post",
                    data: {
                        Data: TableName,
                        Condition: primary_key + "='" + row[primary_key] + "'"
                    },
                    success: (res) => {
                        if (res.length == 1) {
                            res[0].Is_Sticky = (row.Is_Sticky == '0' ? '1' : '0');
                            let lJSONObject_DataSet = new Object();
                            let lJSONObject_Table = new Object();
                            lJSONObject_Table[TableName] = res;
                            lJSONObject_DataSet['Modify'] = lJSONObject_Table;
                            let Operation_Main = JSON.stringify(deepClone(lJSONObject_DataSet));
                            if (!lJSONObject_DataSet['Add']) {
                                lJSONObject_DataSet['Add'] = new Object();
                            }
                            lJSONObject_DataSet['Add']['base_operation_log'] = [{
                                Operation_Type: '0',
                                Operation_Path: this.relativePath,
                                Operation_Main,
                                Operation_Interface: "generalSave",
                                Operation_IP: getIpAddress()
                            }]
                            submitSave(lJSONObject_DataSet,(res)=>{
                                if (res.Status == 'success') {
                                    this.postgetList(this.page);
                                } else {
                                    this.$message({
                                        type: 'error',
                                        message: '操作失败'
                                    });
                                }
                            })
                            // $.ajax({
                            //     headers: requestHeaders(),
                            //     url: `${mh}/generalBusiness/generalSave`,
                            //     method: "post",
                            //     data: {
                            //         Data: JSON.stringify(lJSONObject_DataSet),
                            //     },
                            //     success: (res) => {
                            //         if (res.Status == 'success') {
                            //             this.postgetList(this.page);
                            //         } else {
                            //             this.$message({
                            //                 type: 'error',
                            //                 message: '操作失败'
                            //             });
                            //         }
                            //     },
                            //     complete: (XMLHttpRequest) => {

                            //         requestPretreatment(XMLHttpRequest);
                            //     }
                            // });
                        } else {
                            this.$message({
                                type: 'error',
                                message: '操作失败'
                            });
                        }

                    }, complete: (XMLHttpRequest) => {

                        requestPretreatment(XMLHttpRequest);
                    }
                });
            }).catch(() => { });
        },
    },
};

const { createApp } = Vue;
const app = createApp(App);
//这种方式是引入全部图标，无需单个引入
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
    app.component(key, component);
}
app.component('yl-online-preview', ylOnlinePreview);
const ElMessage = ElementPlus.ElMessage;
app.use(ElementPlus, { locale: zhCn });
app.mount("#app");
